package com.boby.homecamera.fragment.client

import android.Manifest
import android.R.attr.minDate
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.boby.homecamera.R
import com.boby.homecamera.activity.client.CameraClientActivity
import com.boby.homecamera.adapter.VideoEventAdapter
import com.boby.homecamera.db.VideoEventTable
import com.boby.homecamera.db.VideoTable.Video
import com.boby.homecamera.helper.AudioRecoderHelper
import com.boby.homecamera.net.Api
import com.boby.homecamera.util.DateUtil
import com.boby.lib_common.base.BaseActivity
import com.boby.lib_common.extens.toast
import com.boby.lib_common.network.Net
import com.boby.lib_common.util.BLog
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.loper7.date_time_picker.dialog.CardWeekPickerDialog.Companion.CARD
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class VideoEventMsgFragment : Fragment() {
    private var ip: String? = null
    private var token: String? = null
    private var httpPort: Int? = null
    companion object {
        @JvmStatic
        fun newInstance(ip: String, token: String?,httpPort:Int) = VideoEventMsgFragment().apply {
            arguments = Bundle().apply {
                putString("ip", ip)
                putString("token", token)
                putInt("httpPort", httpPort)
            }
        }
        val TAG = "VideoEventMsgFragment"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ip = arguments?.getString("ip")
        token = arguments?.getString("token")
        httpPort = arguments?.getInt("httpPort")
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.view_real_time, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        initData()
    }



    //语音，截屏？，闪光灯，//消息列表
    private lateinit var tv_flashlight: TextView
    private lateinit var tv_voice_call: TextView
    private lateinit var tv_msg_type_person: TextView
    private lateinit var tv_msg_type_sound: TextView
    private lateinit var tv_msg_type_cry: TextView
    private lateinit var tv_date: TextView
    private lateinit var rv_event_msg: RecyclerView
    private var flashOn = false
    private var audioCall = false
    private val videoEventAdapter  = VideoEventAdapter()
    private var isLoadData = false
    private var originVideoEventData: MutableList<VideoEventTable.VideoEvent> = mutableListOf()
    private val todayDate = DateUtil.getTodayStartTimeMillis()
    private var selectDate = todayDate
    private fun initView(rootView:View){
        tv_flashlight = rootView.findViewById(R.id.tv_flashlight)
        tv_voice_call = rootView.findViewById(R.id.tv_voice_call)
        rv_event_msg = rootView.findViewById(R.id.rv_event_msg)
        tv_msg_type_person = rootView.findViewById(R.id.tv_msg_type_person)
        tv_msg_type_sound = rootView.findViewById(R.id.tv_msg_type_sound)
        tv_msg_type_cry = rootView.findViewById(R.id.tv_msg_type_cry)
        tv_date = rootView.findViewById(R.id.tv_date)

        rv_event_msg.adapter = videoEventAdapter
        rv_event_msg.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL,false)

        tv_voice_call.setOnClickListener {
            if(audioCall){
                stopAudioRecoder()
            }else{
                startAudioRecoder()
            }
            tv_voice_call.isSelected = audioCall

        }

        tv_flashlight.setOnClickListener {
            flashOn = !flashOn
            tv_flashlight.isSelected = flashOn
            if(activity is CameraClientActivity){
                (activity as CameraClientActivity).setFlash(flashOn)
            }
        }
        tv_msg_type_person.isSelected = true
        tv_msg_type_sound.isSelected = true
        tv_msg_type_cry.isSelected = true
        tv_msg_type_person.setOnClickListener {
            tv_msg_type_person.isSelected = !tv_msg_type_person.isSelected
            setAdapterData()
        }
        tv_msg_type_sound.setOnClickListener {
            tv_msg_type_sound.isSelected = !tv_msg_type_sound.isSelected
            setAdapterData()
        }
        tv_msg_type_cry.setOnClickListener {
            tv_msg_type_cry.isSelected = !tv_msg_type_cry.isSelected
            setAdapterData()
        }

        tv_date.setOnClickListener {
            if(startFileDate == -1L){
                getVideoStartFileDate()
            }else{
                showDatePicker(startFileDate)
            }

        }
    }

    private fun showDatePicker(minDate:Long){
        CardDatePickerDialog.builder(requireContext())
            .setTitle("选择日期")
            .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY)
            .setBackGroundModel(CARD)
            .showBackNow(false)
//                .setPickerLayout(layout)
            .setDefaultTime(selectDate)
            .setMaxTime(todayDate)
                .setMinTime(minDate)
            .setWrapSelectorWheel(false)
//                .setThemeColor(color)
//                .setAssistColor(color)
//                .setDividerColor(color)
            .setChooseDateModel(DateTimeConfig.DATE_DEFAULT)
            .showDateLabel(false)
            .showFocusDateInfo(false)
            .setTouchHideable(false)
//                .setLabelText("年","月","日")
            .setOnChoose("选择"){millisecond->
//                    BLog.d(TAG,"millisecond: $millisecond ,todayDate:$todayDate")
                selectDate = millisecond
                if(millisecond == todayDate){
                    loadVideoAudioEvent(selectDate,System.currentTimeMillis())
                }else{
                    loadVideoAudioEvent(selectDate,millisecond + 24 * 60 * 60 * 1000)
                }
                tv_date.text =  SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(selectDate))


            }
            .setOnCancel("关闭") {

            }
            .build().show()
    }
    private fun initData(){
        tv_date.text =  SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(selectDate))

        videoEventAdapter.setItemClickListener { index, item ->
            if(activity is CameraClientActivity){

                loadVideoList(item.startTime,item.startTime + 30_000)
            }
        }
        videoEventAdapter.setIp(ip!!,token!!,httpPort!!)
        loadVideoAudioEvent(selectDate,System.currentTimeMillis())
    }
    private var startFileDate = -1L

    private fun getVideoStartFileDate(){
        (activity as BaseActivity).showLoading("")
        Api.getVideoStartFileDate(Api.getRealUrl(ip,httpPort!!),token, object : Net.CallBack<Long>{
            override fun onSuccess(result: Long) {
                BLog.d(TAG,"getVideoStartFileDate onSuccess: ${result}  ")
                (activity as BaseActivity).hideLoading()
                if(result!=-1L){
                    startFileDate = DateUtil.getDayStartTimeMillis( result)
//                    startFileDate = result
                    showDatePicker(startFileDate)
                }

            }

            override fun onError(code: Int, error: String?) {
                BLog.d(TAG,"getVideoStartFileDate onError: ${code}  $error")
                (activity as BaseActivity).hideLoading()
            }

        })
    }

    private fun loadVideoList(startTime:Long,endTime:Long){
        (activity as BaseActivity).showLoading("")
        Api.getVideoList(Api.getRealUrl(ip,httpPort!!),token,startTime,endTime, object : Net.CallBack<List<Video>>{
            override fun onSuccess(result: List<Video>) {
                BLog.d(TAG,"loadVideoList onSuccess: ${result.size}  ")
                (activity as BaseActivity).hideLoading()
                if(result.isEmpty()){
                    toast("请稍后再试")
                }else{
                    val firstStartTime = result.get(0).startTime!!
                    (activity as CameraClientActivity).playVideoMsg(result,startTime - firstStartTime)
                }


            }

            override fun onError(code: Int, error: String?) {
                BLog.d(TAG,"loadVideoList onError: ${code}  $error")
                (activity as BaseActivity).hideLoading()
            }

        })
    }

      fun addNewVideoEvent(event: VideoEventTable.VideoEvent){
//          BLog.d(TAG,"addNewVideoEvent: $videoEvent isLoadData:$isLoadData")
          if(!isLoadData){
              return
          }
          if(selectDate != todayDate){
              return
          }
          tv_flashlight.post {
              originVideoEventData.add(0,event)
              if(tv_msg_type_cry.isSelected && event.eventType == 2){
                  videoEventAdapter.data.add(0,event)
              }else if(tv_msg_type_person.isSelected && event.eventType == 4){
                  videoEventAdapter.data.add(0,event)
              }else if(tv_msg_type_sound.isSelected && event.eventType == 1){
                  videoEventAdapter.data.add(0,event)
              }
              videoEventAdapter.notifyItemInserted(0)
              rv_event_msg.scrollToPosition(0)

          }

    }
    private fun setAdapterData(){
        videoEventAdapter.data.clear()
        if(tv_msg_type_cry.isSelected && tv_msg_type_person.isSelected && tv_msg_type_sound.isSelected){
            videoEventAdapter.data.addAll(originVideoEventData)
        }else{
            for (event in originVideoEventData) {
                if(tv_msg_type_cry.isSelected && event.eventType == 2){
                    videoEventAdapter.data.add(event)
                }else if(tv_msg_type_person.isSelected && event.eventType == 4){
                    videoEventAdapter.data.add(event)
                }else if(tv_msg_type_sound.isSelected && event.eventType == 1){
                    videoEventAdapter.data.add(event)
                }
            }
        }

        videoEventAdapter.notifyDataSetChanged()
    }
    private fun loadVideoAudioEvent(startTime:Long,endTime:Long){
        (activity as BaseActivity).showLoading("加载中...")
        val videoEvent = "1,2,4"
        Api.getVideoEventList(Api.getRealUrl(ip,httpPort!!),token,videoEvent,startTime,endTime, false,object : Net.CallBack<List<VideoEventTable.VideoEvent>>{
            override fun onSuccess(result: List<VideoEventTable.VideoEvent>) {
                BLog.d(TAG,"loadVideoEventList onSuccess: ${result.size}  ")
//                loadVideoPersonEvent(result,startTime,endTime)
                (activity as BaseActivity).hideLoading()
                originVideoEventData.clear()
                originVideoEventData.addAll( result)
                setAdapterData()
                isLoadData = true
            }

            override fun onError(code: Int, error: String?) {
                BLog.d(TAG,"loadVideoList onError: ${code}  $error")
                (activity as BaseActivity).hideLoading()
                isLoadData = true
            }

        })
    }

    private var audioRecoderHelper: AudioRecoderHelper? = null

    private fun startAudioRecoder(){
       if(audioRecoderHelper != null){
           return
       }
        if (ActivityCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.RECORD_AUDIO), 1006)
            return
        }

        audioRecoderHelper = AudioRecoderHelper({
            if(activity is CameraClientActivity){
                (activity as CameraClientActivity).sendAudioMsg(it)
            }
        })
        (activity as CameraClientActivity).setAudioCall(true)
        audioRecoderHelper?.start()
        audioCall = true
    }

    private fun stopAudioRecoder(){
        if(activity is CameraClientActivity){
            (activity as CameraClientActivity).setAudioCall(false)
        }
        audioRecoderHelper?.stop()
        audioRecoderHelper = null
        audioCall = false
    }


}